//
//  TestWebController.m
//  ApeExample
//
//  Created by Eton on 2017/8/15.
//  Copyright © 2017年 王-庭协. All rights reserved.
//

#import "TestWebController.h"

@interface TestWebController ()<UIWebViewDelegate>{
    UIButton * _backButton;
    NSURL * _willLoadURL;
}
@property (assign, nonatomic) NSUInteger loadCount;
@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation TestWebController

- (instancetype)initWithUrl:(NSString *)url withTitle:(NSString *)title {
    
    self = [super init];
    if (self) {
        self.title = title;
        url = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        _homeURL = [NSURL URLWithString:url];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configUI];
    
    _backButton = [self crateBackButton];
    
    if (self.homeURL) {
        NSURLRequest *request = [NSURLRequest requestWithURL:_homeURL];
        [self.webView loadRequest:request];
    }else if(self.homeHTML){
        [self.webView loadHTMLString:self.homeHTML baseURL:nil];
    }
}

- (void)setHomeURL:(NSURL *)homeURL{
    _homeURL = homeURL;
    
    NSLog(@"HomeUrl:%@ \n",homeURL);
    NSURLRequest *request = [NSURLRequest requestWithURL:_homeURL];
    [self.webView loadRequest:request];
}

- (void)setHomeHTML:(NSString *)homeHTML{
    _homeHTML = homeHTML;
    [self.webView loadHTMLString:homeHTML baseURL:nil];
}

- (void)configUI {
    
    // 进度条
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
    progressView.tintColor = self.progressColor;
    progressView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
    
    // 网页
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,  self.view.frame.size.width, self.view.frame.size.height)];
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    webView.scalesPageToFit = YES;
    webView.backgroundColor = [UIColor whiteColor];
    webView.delegate = self;
    [self.view insertSubview:webView belowSubview:progressView];
    self.webView = webView;
}

- (void)reloadColseItem{
    if (self.homeURL && _willLoadURL && [_willLoadURL.absoluteString isEqualToString:self.homeURL.absoluteString]) {
        NSMutableArray *leftItems = [NSMutableArray arrayWithArray:self.navigationItem.leftBarButtonItems];
        if (leftItems.count > 2) {
            [leftItems removeLastObject];
        }
        self.navigationItem.leftBarButtonItems = leftItems;
    }else{
        if (self.navigationItem.leftBarButtonItems.count < 3 && self.navigationController.viewControllers.count > 1) {
            UIButton *colseBtn = [self addLeftBarText:@"关闭" image:nil clickBlcok:^{
                [super back];
            }];
            [colseBtn setTitleColor:[_backButton titleColorForState:UIControlStateNormal] forState:UIControlStateNormal];
        }
    }
}

#pragma mark - 普通按钮事件

// 返回按钮点击
- (void)back{
    if (self.webView.canGoBack) {
        [self.webView goBack];
        [self reloadColseItem];
    }else {
        [super back];
    }
}

// 关闭按钮点击
- (void)colseBtnPressed:(id)sender {
    [super back];
}

#pragma mark - webView代理

// 计算webView进度条
- (void)setLoadCount:(NSUInteger)loadCount {
    _loadCount = loadCount;
    if (loadCount == 0) {
        CGFloat oldP = self.progressView.progress;
        CGFloat sec = (1.0 - oldP) * 2.2;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.hidden = YES;
        });
        [self.progressView setProgress:1.0 animated:YES];
    }else {
        self.progressView.hidden = NO;
        CGFloat oldP = self.progressView.progress;
        CGFloat newP = (1.0 - oldP) / (loadCount + 1) + oldP;
        if (newP > 0.95) {
            newP = 0.95;
        }
        [self.progressView setProgress:newP animated:YES];
    }
}


- (void)webViewDidStartLoad:(UIWebView *)webView {
    self.loadCount ++;
    [self reloadColseItem];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.loadCount = 0;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    self.loadCount --;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    _willLoadURL = request.URL;
    return YES;
}



@end
